package Controller;

import Data.*;
import MyInterfaces.MassageType;
import Service.ClientConnectionServer;
import Service.GetMassage;
import Service.Main;
import Service.SendMassage;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;

public class loginController {

    @FXML
    private Button ensureButton;

    @FXML
    private TextField accountName;

    @FXML
    private TextField textpassword;
    @FXML
    private Button closeButton;

    @FXML
    private PasswordField passwordField;
    @FXML
    private Button cansee;
    @FXML
    private Button notsee;

    public static ArrayList<PrivateInformationData> friendlist;
    @FXML
    private Button forgetpassword;
    private static PrivateInformationData mydata;
    public static PrivateInformationData getMydata()
    {
        return mydata;
    }

    private static Socket socket;
    public static void init(Socket socket) {
        loginController.socket=socket;
    }

    public static Socket getSocket() {
        return socket;
    }

    String id;
    String userPwd;

    public void ensureAction(javafx.event.ActionEvent actionEvent) throws Exception {
        id=accountName.getText();
        if(textpassword.isVisible()) userPwd=textpassword.getText();
        else userPwd=passwordField.getText();
        if(id.equals("")||userPwd.equals(""))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("账号或者密码不可以为空!");
            alert.showAndWait();
            return ;
        }

        //发送确认登录
        System.out.println("发送请求成功");

        event massage=new event();
        massage.setType(MassageType.Request_Login);
        LoginData loginData=new LoginData(id,userPwd);
        massage.setT(loginData);
        //发送消息
        SendMassage send=new SendMassage();
        send.sendMassage(massage);

        //得到一个回应
        event returnmassage=new GetMassage().getMassage();
        System.out.println(returnmassage.getType());
        if(returnmassage.getType().equals(MassageType.Return_Login_Fail))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("账号或者密码错误错误!");
            alert.showAndWait();
        }
        else if(returnmassage.getType().equals(MassageType.Return_Repeat_Login))
        {
            System.out.println("重复登录");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("重复登录!");
            alert.showAndWait();
        }
        else if(returnmassage.getType().equals(MassageType.Return_Init_Information))
        {
            //获得个人信息列表，说明登录成功
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("成功");
            alert.setHeaderText(null);
            alert.setContentText("登录成功!");
            alert.showAndWait();

            Stage stage = (Stage) ensureButton.getScene().getWindow();
            stage.close();

            //拆解消息
            InitChatData initChatData=(InitChatData) returnmassage.getT();
            FriendListData friendListData=initChatData.getFriendListData();
            ArrayList<GroupData> arrayList=initChatData.getGroupDataArrayList();
            friendlist=friendListData.getFriendList();
            mydata=friendListData.getMydata();
            System.out.println(mydata.getUserid());

            ArrayList<String> sentenceList=initChatData.getCommmonSentence();

            System.out.println("收到了好友列表和群聊列表");

            //加载主界面
            Stage primaryStage=new Stage();
            File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\ChatMain.fxml");
            URL location=file.toURI().toURL();
            FXMLLoader fxmlLoader=new FXMLLoader();
            fxmlLoader.setLocation(location);
            Parent root = fxmlLoader.load();
            primaryStage.setTitle("主界面");
            primaryStage.setResizable(false);
            primaryStage.setScene(new Scene(root,400,700));
            primaryStage.show();
            ChatMain chatMain=fxmlLoader.getController();

            Main.AllContronller.setChatMainController(chatMain);
            chatMain.setSocket(socket);
            chatMain.setChatStage(mydata,friendlist);
            chatMain.setCommonSentence(sentenceList);
            //进入线程读取消息

            System.out.println("正在设置群聊界面");
            chatMain.setGroupStage(arrayList);

            Thread myThread=new Thread(new ClientConnectionServer(socket,mydata.getUserid()));
            myThread.start();

            //设置点击关闭窗口的事件
            primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent event) {
                    System.out.println("要退出登录了");

                    try {
                        //告诉服务器我需要退出了
                        event massage=new event();
                        massage.setType(MassageType.Exit);

                        massage.setT(friendListData);
                        new SendMassage().sendMassage(massage);

                        myThread.interrupt();
                        System.exit(0);
                        socket.close();
                        stage.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    //    System.out.print("监听到窗口关闭");
                }
            });

        }

    }

    public void closeAction(javafx.event.ActionEvent actionEvent) throws IOException {

        Stage stage = (Stage) closeButton.getScene().getWindow();
        stage.close();
        socket.close();
    }

    public void forgetpasswordAction(javafx.event.ActionEvent actionEvent) throws IOException, SQLException, ClassNotFoundException {
        Stage stage = (Stage) forgetpassword.getScene().getWindow();
        stage.close();
        File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\ResetPwd.fxml");
        URL newurl = file.toURI().toURL();
        FXMLLoader fxmlLoader=new FXMLLoader();
        fxmlLoader.setLocation(newurl);
        Parent root= fxmlLoader.load();
        Scene scene = new Scene(root,600,400);
        Stage newstage = new Stage();
        newstage.setTitle("忘记密码");
        newstage.setResizable(false);
        newstage.setScene(scene);
        newstage.show();
        //把重置密码的控制类给了Allcontroller
        Main.AllContronller.setResetPwdController(fxmlLoader.getController());

        newstage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                try {
                    event data=new event();
                    data.setType(MassageType.Exit);

                    new SendMassage().sendMassage(data);

                    System.exit(0);
                    socket.close();
                    newstage.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        ResetPwd.init(socket);
    }

    public void CanSeeAction1(javafx.event.ActionEvent actionEvent) {
        cansee.setVisible(false);
        textpassword.setVisible(false);
        notsee.setVisible(true);
        passwordField.setText(textpassword.getText());
        passwordField.setVisible(true);
    }

    public void NotSeeAction1(javafx.event.ActionEvent actionEvent) {

        cansee.setVisible(true);
        textpassword.setText(passwordField.getText());
        textpassword.setVisible(true);
        notsee.setVisible(false);
        passwordField.setVisible(false);

    }

    public void registerAction(javafx.event.ActionEvent actionEvent) throws IOException {
        Stage stage = (Stage) forgetpassword.getScene().getWindow();
        stage.close();
        File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\register.fxml");
        URL location=file.toURI().toURL();
        FXMLLoader fxmlLoader=new FXMLLoader();
        fxmlLoader.setLocation(location);

        Stage newstage=new Stage();
        Parent root = fxmlLoader.load();
        newstage.setTitle("注册");
        newstage.setResizable(false);
        newstage.setScene(new Scene(root,619,486));
        newstage.show();
        Main.AllContronller.setRegisterController(fxmlLoader.getController());

        //重写方法
        newstage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                try {
                    event data=new event();
                    data.setType(MassageType.Exit);

                    new SendMassage().sendMassage(data);

                    socket.close();
                    newstage.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        RegisterController.init(socket);
    }
}
